<?php

class CategoriesController extends \BaseController {

	/**
	 * Display a listing of categories
	 *
	 * @return Response
	 */
	public function index()
	{
		$categories = Category::with('jobs')->get();

		$get_restore_id = Input::get('restore_id');
		if (!empty($get_restore_id)){
			Category::withTrashed()->where('id', $get_restore_id)->restore();
			Category::find($get_restore_id)->jobs()->withTrashed()->where('category_id', $get_restore_id)->restore();
            return Redirect::route('admin.category.index')->with('message', '撤销删除成功');
		}

		return View::make('categories.index', compact('categories'));
	}

	/**
	 * Show the form for creating a new category
	 *
	 * @return Response
	 */
	public function create()
	{
		return View::make('categories.create');
	}

	/**
	 * Store a newly created category in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$validator = Validator::make($data = Input::all(), Category::$rules);

		if ($validator->fails())
		{
			return Redirect::back()->withErrors($validator)->withInput()->with('error', '添加失败');;
		}

		Category::create($data);

		return Redirect::route('admin.category.index')->with('message', '添加成功');
	}

	/**
	 * Display the specified category.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$category = Category::findOrFail($id);

		return View::make('categories.show', compact('category'));
	}

	/**
	 * Show the form for editing the specified category.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$category = Category::find($id);

		return View::make('categories.edit', compact('category'));
	}

	/**
	 * Update the specified category in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$category = Category::findOrFail($id);

		$validator = Validator::make($data = Input::all(), Category::$rules);

		if ($validator->fails())
		{
			return Redirect::back()->withErrors($validator)->withInput();
		}

		$category->update($data);

		return Redirect::route('admin.category.index');
	}

	/**
	 * Remove the specified category from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$category = Category::find($id);
		
		if( !$category )
		{
			return Redirect::route('admin.category.index')->with('error', '对不起，没找到相关的分类');
		}

		$category->jobs()->delete();

		$category->delete();

		return Redirect::route('admin.category.index')->with('message', '删除成功。<a href="?restore_id='.$category->id.'">点击这里撤销删除</a>。');
	}

}
